<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header('Connection: keep-alive');

try {
    $host = $_GET['host'] ?? '';
    $username = $_GET['username'] ?? '';
    $password = $_GET['password'] ?? '';
    $script = $_GET['script'] ?? '';

    // 连接到Python Socket服务器
    $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
    if ($socket === false) {
        throw new Exception("socket_create() failed");
    }

    if (!socket_connect($socket, '127.0.0.1', 5001)) {
        throw new Exception("无法连接到SSH服务器");
    }

    // 发送参数到Python服务器
    $params = json_encode([
        'host' => $host,
        'username' => $username,
        'password' => $password,
        'script' => $script
    ]);
    socket_write($socket, $params, strlen($params));

    // 读取并转发输出
    while (true) {
        $output = socket_read($socket, 4096);
        if ($output === false || $output === '') {
            break;
        }
        echo "data: " . $output . "\n\n";
        ob_flush();
        flush();
    }

} catch (Exception $e) {
    echo "data: 错误: " . $e->getMessage() . "\n\n";
} finally {
    if (isset($socket)) {
        socket_close($socket);
    }
    ob_flush();
    flush();
}
